package com.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/11.
 */
public class TimeServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);
        String boby = new String(req, "UTF-8");
        System.out.println("服务器收到消息：" + boby);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //current
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(boby) ?
                sdf.format(new Date(System.currentTimeMillis())).toString() : "222";

        //Unpooled缓冲池的池方式拿到一个 ByteBuf发生缓冲池
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());

        //ChannelHandlerContext上下文缓冲池里面的内容写给客户端
        ctx.writeAndFlush(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
